﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using Newtonsoft.Json;
using System.Text;
using System.Web;

namespace Mangox.Common
{
    public static class NameValueCollectionEntityMapperHelper
    {
        public static T To<T>(this NameValueCollection kv) where T : class
        {
            if (kv == null || kv.Count == 0)
            {
                return default(T);
            }
            Type t = typeof(T);
            var obj = Activator.CreateInstance(t) as T;
            foreach (var key in kv.Keys)
            {
                var pi = t.GetProperty(key.ToString());
                if (pi != null)
                {
                    string value = HttpUtility.UrlDecode(kv[key.ToString()]);
                    if (pi.PropertyType.IsClass && !pi.PropertyType.Equals(typeof(string)))
                    {
                        pi.SetValue(obj, JsonConvert.DeserializeObject(value, pi.PropertyType), null);
                    }
                    else
                    {
                        pi.SetValue(obj, Convert.ChangeType(HttpUtility.UrlDecode(kv[key.ToString()]), pi.PropertyType), null);
                    }
                }
            }
            return obj;
        }
    }
}
